package com.ww;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class mongoTest {
    public static void main(String[] args) {
        try {
            MongoClient client = new MongoClient("localhost", 27017);
            //连接数据库
            MongoDatabase db = client.getDatabase("test");
            //获取集合
            MongoCollection<Document> course = db.getCollection("course");
            //排序，加上basicDBObject，1为正序，-1为降序
            FindIterable<Document> documents = course.find().sort(new BasicDBObject("id",1));
            //遍历集合内容
            for (Document document : documents) {
                System.out.println(document);
            }
            System.out.println("分割---------------------上面是完整的集合");
            //limit 只取前5条
//            FindIterable<Document> documents = course.find().sort(new BasicDBObject("id",1)).limit(5);
//            //遍历集合内容
//            for (Document document : documents) {
//                System.out.println(document);
//            }
            //跳过前2条后取前5条
            FindIterable<Document> documents2 = course.find().sort(new BasicDBObject("id",1)).limit(5).skip(2);
            //遍历集合内容
            for (Document document : documents2) {
                System.out.println(document);
            }
//            Document document = new Document("name", "单片机");
//            document.append("授课老师", "刘栋");
//            Document document2 = new Document("name", "组成原理");
//            document2.append("授课老师", "陆景天");
//            List<Document> documentList=new ArrayList<>();
//            documentList.add(document);
//            documentList.add(document2);
//            //批量插入
//            course.insertMany(documentList);
//            System.out.println("插入集合成功");
            //更新
//            course.updateOne(Filters.eq("授课老师","王建"),new Document("$set",new Document("name","redis")));
//            System.out.println("执行更新");
//            for (Document document : documents) {
//                System.out.println(document);
//            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
